import json
from utils.qiniu_file import qiniu_token
import redis
from celery_tas.Celery.celery import sms_code
from utils.captcha import Captcha
from io import BytesIO
from flask import Blueprint, jsonify, g, request, make_response
from werkzeug.security import generate_password_hash, check_password_hash
from flask_restful import Api,Resource, reqparse,marshal
from utils.jwt_util import _generate_token, check_token
from models import db
from models.user import *
from models.Courses import *
from utils.login_utils import login_required
from utils.model_fields.user import chapter_fields
from utils.qiniu_file import qiniu_token

user_bp = Blueprint('ubp',__name__,url_prefix='/user')
api = Api(user_bp)


# 获取验证码
class Sms_code(Resource):
    def get(self):
        mobile = request.args.get('phone')
        print('mobile>>>>', mobile)
        sms, _ = sms_code(mobile)
        redis_com = redis.Redis()
        sms_ = redis_com.get(mobile)
        print(sms, "<<<<<>>>>>", _)
        if sms_ is None:
            redis_com.set(mobile, sms, ex=60)
            redis_com.close()
            return sms
        redis_com.close()
        return jsonify(msg="重复发送验证码", code=204)


# 注册
class Register(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('password')
        parser.add_argument('username')
        parser.add_argument('code')
        parser.add_argument('phone')
        args = parser.parse_args()
        pwd = args.get('password')
        username = args.get('username')
        code = args.get('code')
        mobile = args.get('phone')
        redis_com = redis.Redis()
        sms_ = redis_com.get(mobile)
        user_ = UserModels.query.filter_by(phone=mobile).first()
        print(code)
        if user_:
            # 户松遥
            print("重复注册")
            return jsonify(code=204, msg='该用户已存在')
        if sms_:
            if sms_.decode('utf-8') == code:
                password = generate_password_hash(pwd)
                user = UserModels(password=password, account=username, phone=mobile)
                db.session.add(user)
                db.session.commit()
                return '注册成功'
        else:
            print("验证码过期")
            return jsonify(code=204, msg='验证码已过期')


# 图片验证码
class Picture(Resource):
    def get(self):
        uuid = request.args.get('uuid')
        print('uuid>>>>', uuid)
        text, image = Captcha.gene_graph_captcha()
        out = BytesIO()
        image.save(out, 'png')
        out.seek(0)
        resp = make_response(out.read())
        resp.content_type = 'image/png'
        redis_com = redis.Redis()
        redis_com.set(uuid, text, ex=60)
        print(text)
        return resp


class Login(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('password')
        parser.add_argument('account')
        parser.add_argument('img_code')
        parser.add_argument('uuid')
        args = parser.parse_args()
        pwd = args.get('password')
        username = args.get('account')
        code = args.get('img_code')
        uuid = args.get('uuid')
        redis_com = redis.Redis()
        sms_ = redis_com.get(uuid)
        user_ = UserModels.query.filter_by(account=username).first()
        if not user_:
            print("没有该用户")
            return jsonify(code=204, msg='没有该用户')
        if sms_:
            if sms_.decode('utf-8') == code:
                print("验证码验证成功")
                if check_password_hash(user_.password, pwd):
                    payload = {
                        'user_id': user_.uid,
                        'username': user_.account
                    }
                    token, token_ = _generate_token(payload)
                    token_data = {
                        'token': token,
                        'refresh_token': token_
                    }
                    return jsonify(data={'token': token, "account": username, "uid": user_.uid}, code=200, msg='登录成功', username=username)
                else:
                    print("密码有误")
                    return '密码有误'
            else:
                print("验证码有误")
                return jsonify(code=204, msg='验证码有误')
        else:
            print("验证码过期")
            return jsonify(code=204, msg='验证码已过期')


# 该课程的学习进度
class SectionsanDuer(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        list1 = ["cid", "token"]
        for i in list1:
            parser.add_argument(i)
        args = parser.parse_args()
        com_id = args.get('cid')
        token = args.get('token')
        payload = check_token(token[4:])
        user_id = payload.get('user_id')

        learn_list = []
        # 生成课程信息
        course_ = Course.query.filter_by(id=com_id).first()

        # 生成课程的章程信息
        chapter_ = Chapters.query.filter_by(course=course_.id).all()
        section_ser = []
        for i in chapter_:
            section_ser.append(marshal(i, chapter_fields))
        section_ser_dict = json.loads(json.dumps(section_ser))
        for i in section_ser_dict:
            # 章节的小节
            data = []
            sections_ = Sections.query.filter_by(chapters=i.get('id')).all()
            for j in sections_:
                sectionsanduser = SectionsandUser.query.filter_by(user_id=user_id, sections_id=j.id, guankan=1).first()
                if sectionsanduser:
                    data_ = {
                        'sid': j.id
                    }
                    data.append(data_)
            if len(sections_) == len(data):
                learn_list.append(data)
        print("学习进度》》》》》》》》》》》》》》》》》》", learn_list)
        return jsonify(data=learn_list, code=200)


# 用户头像上传七牛云
class User_Info_Post(Resource):
    def get(self):
        token = qiniu_token()
        return jsonify(message='ok', code=200, data={'token': token})


api.add_resource(Sms_code, '/phone_code')
api.add_resource(Register, '/register_user')
api.add_resource(Picture, '/code')
api.add_resource(Login, '/login')
api.add_resource(SectionsanDuer, '/learninfo/')
api.add_resource(User_Info_Post, '/uptoken/')


